import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs, make_circles, make_moons

data_generated_functions = {
    "make_blobs": make_blobs(n_samples=400, centers=2, random_state=42),
    "make_circles": make_circles(n_samples=400, random_state=42),
    "make_moons": make_moons(n_samples=400, random_state=42)
}

C_values = [0.01, 0.1, 1, 10, 100, 1000]

if __name__ == '__main__':
    for data_name, data_generated_function in data_generated_functions.items():
        features, labels = data_generated_function
        for C in C_values:
            svm_classifier = svm.SVC(C=C)
            svm_classifier.fit(features, labels)
            print(f"C value: {C}, Support vectors: {svm_classifier.support_}")
            plt.scatter(features[:, 0], features[:, 1], c=labels, s=30)
            # 绘制决策函数
            ax = plt.gca()
            x_lim = ax.get_xlim()
            y_lim = ax.get_ylim()
            print(x_lim, y_lim)
            # 网格化评价模型
            x_grid = np.linspace(x_lim[0], x_lim[1], 30)
            y_grid = np.linspace(y_lim[0], y_lim[1], 30)
            Y_grid, X_grid = np.meshgrid(y_grid, x_grid)  # 创建网格
            grid_points = np.vstack([X_grid.ravel(), Y_grid.ravel()]).T  # 组合网格坐标
            decision_values = svm_classifier.decision_function(grid_points).reshape(X_grid.shape)  # 计算决策函数值
            # 绘制分类边界
            ax.contour(X_grid, Y_grid, decision_values, colors='k', levels=[-1, 0, 1], alpha=0.5,
                       linestyles=['--', '-', '--'])
            plt.title(f"SVM with C={C} on {data_name} data")
            plt.show()
